package cn.fxc;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

public class TableLogger {
    private static final Logger logger = LoggerFactory.getLogger(TableLogger.class);

    public static void logAsTable(List<Map<String, String>> data) {
        if (data == null || data.isEmpty()) {
            logger.info("No data to display");
            return;
        }

        // 获取所有列名
        Map<String, String> firstRow = data.get(0);
        String[] columns = firstRow.keySet().toArray(new String[0]);

        // 计算每列的最大宽度
        int[] columnWidths = new int[columns.length];
        for (int i = 0; i < columns.length; i++) {
            columnWidths[i] = columns[i].length();
            for (Map<String, String> row : data) {
                String value = row.get(columns[i]);
                if (value != null && value.length() > columnWidths[i]) {
                    columnWidths[i] = value.length();
                }
            }
        }

        // 构建表头分隔线
        StringBuilder separator = new StringBuilder("+");
        for (int width : columnWidths) {
            separator.append("-".repeat(width + 2)).append("+");
        }

        // 构建表头
        StringBuilder header = new StringBuilder("|");
        for (int i = 0; i < columns.length; i++) {
            header.append(" ").append(padRight(columns[i], columnWidths[i])).append(" |");
        }

        // 记录表头
        logger.info(separator.toString());
        logger.info(header.toString());
        logger.info(separator.toString());

        // 记录每行数据
        for (Map<String, String> row : data) {
            StringBuilder rowBuilder = new StringBuilder("|");
            for (int i = 0; i < columns.length; i++) {
                String value = row.get(columns[i]);
                value = value == null ? "" : value;
                rowBuilder.append(" ").append(padRight(value, columnWidths[i])).append(" |");
            }
            logger.info(rowBuilder.toString());
        }

        // 记录表格底部
        logger.info(separator.toString());
    }

    private static String padRight(String s, int length) {
        return String.format("%-" + length + "s", s);
    }
}